package com.sbl.bajw.common;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {

	public static HSSFWorkbook createExcel(List<HashMap<String, Object>> table,LinkedHashMap<String, String> columns) throws Exception
	{
		HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象  
		HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet对象  
		HSSFRow headRow = sheet.createRow((short)0);//建立新行  		  
		
		int columsIndex = 0;
		Iterator<String> keys = columns.keySet().iterator();
		List<String> columnsName = new ArrayList<String>();
		
		while(keys.hasNext()){
			String columnName = keys.next();
			headRow.createCell(columsIndex).setCellValue(columns.get(columnName));
			columnsName.add(columnName);
			columsIndex++;
		}
		
		for(int j=0;j<table.size();j++)
		{
			HSSFRow row = sheet.createRow((short)(j+1));//建立新行  		  
			HashMap<String, Object> dataItem = table.get(j);
			
			for(int i=0;i<columnsName.size();i++)
			{
				Object valueObj =dataItem.get(columnsName.get(i));
				String value = "";
				if(valueObj != null){
					value = valueObj.toString();
				}
				row.createCell(i).setCellValue(value);
			}
		}
		return wb;
	}
	public static <T extends Object> HSSFWorkbook createMExcel(List<T> modelTable,LinkedHashMap<String, String> columns) throws Exception
	{
		HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象  
		List<HashMap<String, Object>> table = conventModelToMap(modelTable);
		wb = createExcel(table, columns);
		return wb;
	}
	
	private static <T extends Object> List<HashMap<String, Object>> conventModelToMap(List<T> objs) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		@SuppressWarnings("rawtypes")
		Class modelClass = objs.get(0).getClass();
		Field[] fields = modelClass.getDeclaredFields();
		
		List<HashMap<String, Object>> table = new ArrayList<HashMap<String,Object>>();
		
		for(Object obj:objs){
			HashMap<String, Object> map = new HashMap<String, Object>();
			for (Field field : fields) 
			{
				String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
				Method[] methods = modelClass.getMethods();  
				Method method = null;
				
				for (Method m : methods) {
					if(m.getName().equals(methodName))
					{
						method = m;
						break;
					}
				}
				
				if(method == null){
					continue;
				}
				
				Object value = method.invoke(obj);
				map.put(field.getName(), value);
			}
			table.add(map);
		}
		return table;
	}
}